#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from WindPy import w


def ensure_wind_connected(retry, windConnectWaitTime):
    """
    """
    while retry > 0:
        if w.isconnected():
            return ""
        wd = w.start(windConnectWaitTime)
        if wd.ErrorCode == 0:
            return ""
        retry -= 1
    return "Error starting WindPy (w.start()): %s" % wd


def w_tdaysoffset(offset, beginDateStr, inclZeroTd):
    """
    """
    if offset > 0:
        return "offset must <= 0", []
    wd = w.tdaysoffset(offset, beginDateStr, "TradingCalendar=SHFE")
    if wd.ErrorCode != 0:
        return ("Call w.tdaysoffset(%s, %s, \"TradingCalendar=SHFE\") with errors: %s" %
            (offset, beginDateStr, wd), [])
    else:
        endDay = wd.Times[0]
        if offset == 0:
            return "", [endDay.strftime("%Y-%m-%d")]

        tds = w.tdays(endDay.strftime("%Y-%m-%d"), beginDateStr, "TradingCalendar=SHFE")
        if tds.ErrorCode != 0:
            return ("Call w.tdays(%s, %s, \"TradingCalendar=SHFE\") with errors: %s" %
                (endDay.strftime("%Y-%m-%d"), beginDateStr, tds), [])
        else:
            return ("", [e.strftime("%Y-%m-%d") for e in tds.Times] if inclZeroTd else
                [e.strftime("%Y-%m-%d") for e in tds.Times[0:-1]])


def w_tdays(fromDateStr, toDateStr):
    """
    """
    wd = w.tdays(fromDateStr, toDateStr, "TradingCalendar=SHFE")
    if wd.ErrorCode != 0:
        return ("Call w.tdays(%s, %s, \"TradingCalendar=SHFE\") with errors: %s" %
            (fromDateStr, toDateStr, wd), [])
    else:
        return "", [e.strftime("%Y-%m-%d") for e in wd.Times]
